package com.huangd.platform.modules.sys.service.impl;


import com.huangd.platform.common.utils.Constant;
import com.huangd.platform.modules.sys.dao.*;
import com.huangd.platform.modules.sys.entity.SysMenuEntity;
import com.huangd.platform.modules.sys.entity.SysUserTokenEntity;
import com.huangd.platform.modules.sys.entity.TblRoleEntity;
import com.huangd.platform.modules.sys.entity.TblUserEntity;
import com.huangd.platform.modules.sys.service.ShiroService;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class ShiroServiceImpl implements ShiroService {
    @Resource
    private TblRoleDao roleDao;
    @Resource
    private TblUserRoleDao userRoleDao;
    @Resource
    private SysMenuDao sysMenuDao;
    @Resource
    private TblUserDao sysUserDao;
    @Resource
    private SysUserTokenDao sysUserTokenDao;


    @Override
    public Set<String> getUserPermissions(long userId) {
        List<String> permsList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<SysMenuEntity> menuList = sysMenuDao.selectList(null);
            permsList = new ArrayList<>(menuList.size());
            for(SysMenuEntity menu : menuList){
                permsList.add(menu.getPerms());
            }
        }else{
            permsList = sysUserDao.queryAllPerms(userId);
        }
        //用户权限列表
        Set<String> permsSet = new HashSet<>();
        for(String perms : permsList){
            if(StringUtils.isBlank(perms)){
                continue;
            }
            permsSet.addAll(Arrays.asList(perms.trim().split(",")));
        }
        return permsSet;
    }

    @Override
    public Set<String> getUserRoles(long userId) {
        List<String> roleList;

        //系统管理员，拥有最高权限
        if(userId == Constant.SUPER_ADMIN){
            List<TblRoleEntity> roleEntities = roleDao.selectList(null);
            roleList = new ArrayList<>(roleEntities.size());
            for(TblRoleEntity role : roleEntities){
                roleList.add(role.getCode());
            }
        }else{
            roleList = userRoleDao.queryRoleCodeList(userId);
        }
        //用户权限列表
        Set<String> roleSet = new HashSet<>();
        for(String role : roleList){
            if(StringUtils.isBlank(role)){
                continue;
            }
            roleSet.addAll(Arrays.asList(role.trim().split(",")));
        }
        return roleSet;
    }

    @Override
    public Long queryByToken(String token) {

        SysUserTokenEntity userTokenEntity = sysUserTokenDao.queryByToken(token);
        if (userTokenEntity == null) {
            return null;
        } else {
            return userTokenEntity.getUserId();
        }
    }

    @Override
    public TblUserEntity queryUser(Integer userId) {
        return sysUserDao.selectById(userId);
    }
}
